package org.cweili.rayminder.gui

import javax.swing.*
import javax.swing.plaf.FontUIResource
import java.awt.*

/**
 * 图形界面初始化设置
 *
 * @author canghailan ( Modified by Cweili )
 * @datetime 2011-12-19 11:13
 * @version 13-8-23 14:21
 *
 */
@Singleton
class GuiInit {

	static final FALLBACK_FONT_FAMILY_NAME = Font.SANS_SERIF
	static final FONT_FAMILY_NAMES = [:]
	static final BEST_FONT_FAMILIES = ['微软雅黑', 'arial', 'sans-serif']
	static final BEST_FONT_SIZE = 14

	private GuiInit() {
		init()
		setUI()
	}

	private init() {
		def env = GraphicsEnvironment.localGraphicsEnvironment
		def fontFamilyNames = env.availableFontFamilyNames
		for (fontFamilyName in fontFamilyNames) {
			FONT_FAMILY_NAMES.put(fontFamilyName.toLowerCase(), fontFamilyName)
		}
		if (!FONT_FAMILY_NAMES.containsKey('serif')) {
			FONT_FAMILY_NAMES.put('serif', Font.SERIF)
		}
		if (!FONT_FAMILY_NAMES.containsKey('sans-serif')) {
			FONT_FAMILY_NAMES.put('sans-serif', Font.SANS_SERIF)
		}
	}

	private enableAntiAliasing() {
		System.setProperty('awt.useSystemAAFontSettings', 'on')
		System.setProperty('swing.aatext', 'true')
	}

	private getLookAndFeel() {
		try {
			for (info in UIManager.installedLookAndFeels) {
				switch (info.name) {
					case 'Windows':
					case 'GTK+':
					case 'Nimbus':
						return info.className
				}
			}
		} catch (Exception ignore) {
		}
		UIManager.crossPlatformLookAndFeelClassName
	}

	private getFontFamily(fontFamilies) {
		for (fontFamily in fontFamilies) {
			fontFamily = fontFamily.toLowerCase()
			if (FONT_FAMILY_NAMES.containsKey(fontFamily)) {
				return FONT_FAMILY_NAMES.get(fontFamily)
			}
		}
		FALLBACK_FONT_FAMILY_NAME
	}

	/**
	 * 图形界面初始化设置
	 */
	private setUI() {
		enableAntiAliasing()
		// set LookAndFeel
		try {
			UIManager.lookAndFeel = getLookAndFeel()
		} catch (Exception ignore) {
		}
		// set DefaultFont
		String bestFontFamily = getFontFamily(BEST_FONT_FAMILIES)
		for (entry in UIManager.getDefaults().entrySet()) {
			if (entry.getValue() instanceof FontUIResource) {
				def fontUIRes = (FontUIResource) entry.getValue()
				entry.setValue(new FontUIResource(bestFontFamily, fontUIRes.getStyle(),
						BEST_FONT_SIZE > fontUIRes.getSize() ? BEST_FONT_SIZE : fontUIRes
								.getSize()))
			}
		}
	}

}
